package com.wt.order.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wt.order.common.R;
import com.wt.order.entity.Employee;
import com.wt.order.service.EmployeeService;
import com.wt.order.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author 吴涛
 * @date 2022/5/9 14:34
 * @qq 337144203
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    //创建登录方法

    @Autowired
    //private RedisTemplate redisTemplate;
   private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private RedisCache redisCache;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    //从前端接收到的是JSON数据，所以使用RequestBody
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        //1.将页面提交的密码进行md5加密处理
        String password = employee.getPassword();//拿到前端传过来的密码
         password = DigestUtils.md5DigestAsHex(password.getBytes());//使用工具类使用md5将其加密

        //2.根据页面提交的用户名继续查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        //emp是从数据库中查出来的对象
        Employee emp = employeeService.getOne(queryWrapper);//因为注册账号的时候，用户名是唯一的，所以可以使用getOne

        //3.查询失败，返回失败结果
        if (emp==null){
            return R.error("登录失败，用户不存在");
        }

        //4.密码对比，不一致返回登录失败结果
        if (!emp.getPassword().equals(password)){
            return R.error("登录失败,密码错误");
        }

        //5.查看员工状态，如果是禁用状态就返回员工已禁用，不能登录
        if (emp.getStatus()==0){
            return R.error("登录失败,账号已禁用");
        }

        //6.登录成功，将员工id存入session，并登录成功返回结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }


    /**
     * 退出登录功能
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");//获取session中的数据并将其删除
        return R.success("退出成功");//返回相应数据
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工，员工信息{}",employee.toString());
        //设置初始密码为123456。并用md5加密进行处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //设置创建时间，获取系统的当前时间
        //employee.setCreateTime(LocalDateTime.now());
        //设置更新时间时间，获取系统的当前时间
        //employee.setUpdateTime(LocalDateTime.now());

        //获取session中当前用户登录的id
        //Long empId = (Long) request.getSession().getAttribute("employee");
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);
        employeeService.save(employee);
        return R.success("添加成功");
    }

    /**
     *分页查询
     * @param page 当前的页码
     * @param pageSize 每页展示的记录
     * @param name  可选，模糊查询
     * @return
     */
    @GetMapping("page")
    public R<Page> selectPage(int page,int pageSize,String name){

        Page<Employee> pageInfo = new Page(page,pageSize);
        //TODO 使用redis优化这个分页
        String searchKey = page+"_"+pageSize;
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        //先从redis缓存中取数据
        if (name == null){
            String employee = hashOperations.get("employee", searchKey);
            if (employee!=null) {
            Page page1 = JSON.parseObject(employee, Page.class);
                return R.success(page1);
            }
        }
        //如果存在，直接返回
        //如果不存在，则去数据库中查找，将查到的数据缓存到redis
        LambdaQueryWrapper<Employee> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo,queryWrapper);
        if (name ==null){
            String jsonString = JSON.toJSONString(pageInfo);
            hashOperations.put("employee", searchKey,jsonString);
        }
        return R.success(pageInfo);
    }

    @PutMapping()
    public R<String> update(@RequestBody Employee employee){
        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);
        employeeService.updateById(employee);
        return R.success("员工信息更新成功");
    }

    /**
     * 根据id查询并回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        Employee employee1 = employeeService.getById(id);
        if (employee1 !=null ){
            return R.success(employee1);
        }
        return R.error("没有查到相关用户信息");
    }




}
